package class01.test;

import java.util.Arrays;

public class Code04_BSExist {

    public static boolean exist(int[] arr, int num){
        if(arr == null || arr.length == 0){
            return false;
        }
        if(arr[0] > num || arr[arr.length-1] < num){
            return false;
        }
        int L = 0;
        int R = arr.length;
        int mid = 0;
        while (R > L){
            mid = (int)(L + ((R - L) >> 1));
            if(arr[mid] == num) {
                return true;
            }else if(arr[mid] > num){
                R = mid - 1;
            }else {
                L = mid  + 1;
            }
        }

        return arr[R] == num;
    }

    public static void main(String[] args) {
        int testTime = 5000000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = generateRandomArray(maxSize,maxValue);
            Arrays.sort(arr);
            int goal = ((int)((maxValue + 1)*Math.random())) - ((int)((maxValue)*Math.random()));
            if(exist(arr,goal) != test(arr,goal)){
                succeed = false;
                printArray(arr);
                System.out.println(goal);
            }
        }
        System.out.println(succeed?"good":"bad");
    }

    private static void printArray(int[] arr) {
        if(arr == null){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    private static boolean test(int[] arr, int goal) {
        if(arr == null || arr.length == 0){
            return false;
        }
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] == goal){
                return true;
            }
        }
        return false;
    }


    private static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[((int)((maxSize + 1)*Math.random()))];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = ((int)((maxValue + 1)*Math.random())) - ((int)((maxValue)*Math.random()));
        }
        return arr;
    }
}
